package cn.spiral.qz_job.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import cn.spiral.core.dao.impl.BaseDaoImpl;
import cn.spiral.core.service.impl.BaseServiceImpl;
import cn.spiral.qz_job.dao.QzJobDao;
import cn.spiral.qz_job.entity.QzJob;
import cn.spiral.qz_job.service.QzJobService;

@Service("qzJobService")
public class QzJobServiceImpl extends BaseServiceImpl<QzJob> implements QzJobService{

	private QzJobDao qzJobDao;

	@Autowired
	public void setQzJobDao(QzJobDao qzJobDao) {
		super.setBaseDao(qzJobDao);
		this.qzJobDao = qzJobDao;
	}
	
	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;
	
	//quartz是在要执行前才实例化要执行的类，才去数据库读取相应的信息，所以对于任务的更改，删除工作只修改数据库内容即可
	public void addJob(QzJob qzJob){
		qzJobDao.save(qzJob);
		JobDetail jobDetail =JobBuilder.newJob(cn.spiral.qz_job.jobclass.AddJob.class).withIdentity(qzJob.getJobName()).build();
		JobDataMap dataMap=jobDetail.getJobDataMap();
		dataMap.put("jobName", qzJob.getJobName());
		dataMap.put("qzJobService", this);
		SimpleTrigger simpleTrigger=(SimpleTrigger) TriggerBuilder.newTrigger().withIdentity(qzJob.getJobName()).startAt(DateBuilder.dateOf(
					qzJob.getJobStartTime().getHours(),
					qzJob.getJobStartTime().getMinutes(),
					qzJob.getJobStartTime().getSeconds(),
					qzJob.getJobStartTime().getDate(),
					qzJob.getJobStartTime().getMonth(),
					qzJob.getJobStartTime().getYear())
				).build();
		try {
			Scheduler scheduler=schedulerFactoryBean.getScheduler();
			scheduler.scheduleJob(jobDetail, simpleTrigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	//更改状态的方法
	public void changeJobState(String jobId,int state){
		QzJob qzJob = qzJobDao.findObjectById(jobId);
		if(qzJob!=null){
			qzJob.setJobState(state);
			qzJobDao.update(qzJob);
		}
	}
	
	//重新启动服务器时自动执行该方法，对未完成的工作（包括暂停的，因为可能会重新启用，如果任务超时，那么会立即执行，等待执行中的会立即执行，而暂停且超时的会被设置为失效）
	public void autoRecreateJob(){
		
		List<QzJob> list=qzJobDao.findUndoJob();
		for (QzJob qzJob : list) {
			addJob(qzJob);
		}
	}
	
	public QzJob findJobByName(String jobaName){
		return qzJobDao.findJobByName(jobaName);
	}

	//检查excel邮箱内容是否正确
	public ArrayList<Integer> checkExcelcheckExcelEmail(File sendExcel ,String sendExcelFileName) {
		ArrayList<Integer> noList=new ArrayList<Integer>();
		try {
			InputStream inputStream=new FileInputStream(sendExcel);
			boolean is03Excel=sendExcelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook= is03Excel ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);
			Sheet sheet=workbook.getSheetAt(0);
			
			for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
				Row row=sheet.getRow(i);
				String cell=row.getCell(1).getStringCellValue();
				String regex="^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
				if(!cell.matches(regex)){
					//不匹配邮箱格式，记录该错误列
					noList.add(i+1);
				}
			}
			workbook.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			noList.add(0);
		}
		return noList;
	}
	
	//检查excel手机号码内容是否正确
	public ArrayList<Integer> checkExcelcheckExcelPhone(File sendExcel ,String sendExcelFileName) {
		ArrayList<Integer> noList=new ArrayList<Integer>();
		try {
			InputStream inputStream=new FileInputStream(sendExcel);
			boolean is03Excel=sendExcelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook= is03Excel ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);
			Sheet sheet=workbook.getSheetAt(0);
			
			for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
				Row row=sheet.getRow(i);
				String cell=row.getCell(1).getStringCellValue();
				String regex="^[1][358]\\d{9}$";
				if(!cell.matches(regex)){
					//不匹配手机格式，记录该错误列
					noList.add(i+1);
				}
			}
			workbook.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			noList.add(0);
		}
		return noList;
	}
	
	
	
	
	/*	public void test(){

	JobDetail jobDetail =JobBuilder.newJob(cn.spiral.qz_job.jobclass.test.class).withIdentity("testJob").build();
	JobDataMap dataMap=jobDetail.getJobDataMap();
	dataMap.put("jobName", "test");
	dataMap.put("qzJobService", this);
	SimpleTrigger simpleTrigger=(SimpleTrigger) TriggerBuilder.newTrigger().startNow().build();
	try {
		Scheduler scheduler=schedulerFactoryBean.getScheduler();
		scheduler.scheduleJob(jobDetail, simpleTrigger);
	} catch (SchedulerException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	
	}*/
}
